import React, {Component, ComponentClass} from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Button, Navigator, Block, Image, Radio, Icon, Checkbox} from '@tarojs/components';
import {AtInputNumber, AtInput, AtSwitch, AtIcon, AtLoadMore, AtModal, AtModalContent, AtFloatLayout} from 'taro-ui';
import {connect} from 'react-redux';
import {
  OrderInfo, Address, OrderCar, Wallet
} from '../../utils/server.interface';
import {user} from '../../utils/user.service';
import {http} from '../../utils/http';
import {
  GET_PAY_INFO,
  ADDRESS_DEFAULT,
  GET_CAN_USE_COUPONlIST,
  SURE_ORDER,
  ADDRESS_DETAIL,
  WALLET,
  RESOURCE_URL,
  GET_INTEGRAL_JUDGE,
  GET_PHONE,
  CAR_ORDER_QR,
  PC_ORDER_STATUS, TRANS_ORDER_DETAIL, CREATE_AND_PAY, CHECK_GROUP_STATUS,
  GET_AIKUCUN_FREIGHT, TARO_ENV
} from '../../constants/api';
import {DateType} from '../../reducers/select-date';
import {platform} from '../../utils/platform-settting.service';
import SupportBar from "../../components/support-bar/support-bar";
import {getTempSellerId} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {newHttp} from "../../utils/request";
import {payment} from "../../utils/payment.service";
import {location as localtionServer} from '../../utils/location.service';
import {lxH5Wx} from "../../utils/lx.h5.service";
import {getContent} from "../../utils/handlerPublicCode";
import './place.scss';

interface StateType {
  consume_fee: number
  openKD: boolean
  fromOrderNum?: any
  goodsDiscountCodeId?: any
  force_platform_seller?: any
  activityId?: any
  isLeader?: any
  groupPrice?: any
  isChecked?: any
  fromGoodDetail?: any
  type: number
  latitude: number
  longitude: number
  freight: number
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  redbag: any
  orderInfo: any
  orderCar: any
  access: any
  addobj: any
  GOlogin: boolean
  agree: boolean
  remark: string
  sum: number
  isgrade: boolean
  userBalance: boolean
  redbagId: number
  givechecked: boolean
  youhui: number
  formdata: object
  whereSelf: number
  ids?: string
  goodUuid?: any
  recharge: boolean
  canBalance: boolean
  pay: number
  platformSet: any
  custom_config: { keyName: string; required: boolean; name: string; value: string }[]
  isOpenCredit: number
  creditAmount: number
  itegralInfo: any
  couponMoney: number
  offOpenCoupon: boolean
  notUse: boolean
  userOk: number
  couponList: any
  couponIsUseId: number
  couponMoneyName: string
  tempSellerId?: any
  env: string
  pcqrcode: string
  pcQrcodeShow: boolean
  paySuccessShow: boolean
  aikucunFreight: number
  allowDeliver: string
  denyReason: string
  addobjAddress: object
  buyAmount: number
  orderNum: string
  getAikucunFreightCarData: object
  isShowAikucunFreightCar: boolean
  isShowAikucunFreightFreight: boolean
  ikucunFreightCarTotalFreight: number
  orderCarGoods: object
}

type PageStateProps = {
  selectDate: DateType
}

type PageDispatchProps = {}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Confirm {
  props: IProps
}

@connect(({selectDate}) => ({
  selectDate,
}), (dispatch) => ({}))

class Confirm extends Component {
  state: StateType = {
    consume_fee: 0.00,
    openKD: true,
    force_platform_seller: '',
    goodsDiscountCodeId: '',
    fromOrderNum: null,
    fromGoodDetail: null,
    isChecked: false,
    loadMoreStatus: 'loading',
    isgrade: false,
    agree: false,
    redbagId: 0,
    redbag: false,
    freight: 0,
    givechecked: false,
    youhui: 0,
    access: false,
    sum: 0,
    type: 0,
    remark: '',
    latitude: 39.899992,
    longitude: 116.398001,
    whereSelf: -1,
    GOlogin: false,
    platformSet: {
      isShowServicePhone: 0,
      platformServicePhone: '',
      platformName: '',
      platformSellerType: 0,
      platformLogo: '',
      sellerRegType: 0,
      payVersion: 0
    },
    userBalance: false,
    orderCar: {},
    orderInfo: {},
    addobj: false,
    canBalance: false,
    formdata: {},
    recharge: false,
    pay: 0,
    ids: '',
    goodUuid: '',
    custom_config: [],
    isOpenCredit: 0,
    activityId: null,
    isLeader: false,
    groupPrice: 0,
    creditAmount: 0,
    integralInfo: false,
    couponMoney: 0,
    offOpenCoupon: false,
    notUse: false,
    userOk: 1,
    couponList: [],
    couponIsUseId: 0,
    couponMoneyName: '',
    env: '',
    tempSellerId: '',
    pcqrcode: 'string',
    pcQrcodeShow: false,
    paySuccessShow: false,
    aikucunFreight: 0,
    denyReason: '',
    addobjAddress: {},
    buyAmount: 0,
    orderNum: '',
    allowDeliver: '',
    getAikucunFreightCarData: [],
    isShowAikucunFreightCar: true,
    isShowAikucunFreightFreight: false,
    ikucunFreightCarTotalFreight: 0,
    orderCarGoods: {}
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const {type = 0, goodUuid} = this.params
    this.setState({type, goodUuid})
    const platformSet: any = await platform.info
    if (platformSet.platformName) {
      Taro.setNavigationBarTitle({
        title: platformSet.platformName
      })
    }
    const tempSellerId = getTempSellerId(this)
    const goodsDiscountCodeId = this.params.goodsDiscountCodeId || '';
    const force_platform_seller = this.params.force_platform_seller || '';
    await this.setStateSync({goodsDiscountCodeId, force_platform_seller});
    this.setState({tempSellerId, platformSet, agree: !!platformSet.user_agreement_type})
    try {
      localtionServer.getLocation().then(async (res: any) => {
        if (res) {
          this.setState({latitude: res.latitude, longitude: res.longitude});
        }
      });
    } catch (e) {
      await Taro.showModal({
        title: '提示',
        content: '您需要开启手机的GPS定位, 才能为您匹配精准的自提点信息'
      })
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      this.setState({
        GOlogin: true
      })
      await user.jumpLogin()
      return
    }
    if (process.env.TARO_ENV === "weapp") {
      Taro.hideShareMenu()
    }
    await this.getData()
  }

  getMarketPrice() {
    const good = Taro.getStorageSync('placeOrder')
    if (good) {
      return JSON.parse(good).market_price
    }
  }

  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }

  async getAikucunFreight(addobjAddress, buyAmount, orderNum) {
    this.setState({buyAmount: buyAmount, orderNum: orderNum})
    const res = await newHttp.post(GET_AIKUCUN_FREIGHT, {
      province: addobjAddress.province,
      city: addobjAddress.city,
      area: addobjAddress.area,
      buy_amount: buyAmount,
      order_num: orderNum
    })
    this.setState({
      allowDeliver: res.data.allowDeliver,
      denyReason: res.data.denyReason,
      aikucunFreight: res.data.freight
      // aikucunFreight: 2
    })
  }

  getAikucunFreightCar(addobjAddress, orderCarGoods) {
    this.setState({orderCarGoods: orderCarGoods})
    const array = []
    orderCarGoods.map(async (item, index) => {
      const res = await newHttp.post(GET_AIKUCUN_FREIGHT, {
        province: addobjAddress.province,
        city: addobjAddress.city,
        area: addobjAddress.area,
        buy_amount: item.num,
        order_num: item.order_num
      })
      array.push(res.data)
      // array[1].freight = 2
      this.setState({getAikucunFreightCarData: array})
      this.judgeAikucunFreightCar(array)
    })
  }

  judgeAikucunFreightCar(data) {
    let result = true
    let totalFreight = 0
    for (let i = 0; i < data.length; i++) {
      if (!data[i] || data[i].allowDeliver === '0') {
        result = false
        break
      } else {
        totalFreight += data[i].freight
        result = true
      }
    }
    this.setState({isShowAikucunFreightCar: result, ikucunFreightCarTotalFreight: totalFreight})
  }


  async getData() {
    const {
      itemId = 0,
      m = 'product',
      num = 1,
      no = '',
      id,
      type = 0,
      fromOrderNum,
      activityId = '',
      groupBuyId = '',
      isLeader = false,
      stepNum = 0,
      groupPrice
    } = this.params
    const {goodsDiscountCodeId, force_platform_seller} = this.state
    const tempSellerId = getTempSellerId(this)
    this.setState({activityId, isLeader: Number(JSON.parse(isLeader)), groupPrice: Number(groupPrice)})
    let addobjAddress: any = await http.carGet<Address>(ADDRESS_DEFAULT)
    if (!addobjAddress) {
      addobjAddress = false
    }
    this.setState({addobjAddress, loadMoreStatus: 'noMore'})
    if (type == 0) {/* 立即购买按钮进入 */
      let orderInfo: any = {}
      if (!itemId) {
        Taro.showToast({title: '参数错误', icon: 'none'})
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.navigateBack()
        }, 1500)
        return
      }
      let good = Taro.getStorageSync('placeOrder')
      if (good) {
        good = JSON.parse(good)
        orderInfo['img'] = good.img
        orderInfo['id'] = itemId
        orderInfo['title'] = good.name
        orderInfo['num'] = num
        orderInfo['price'] = good.price
        this.setState({orderInfo})
      }
      if (m == "product") {
        orderInfo = await http.postCar<OrderInfo>(GET_PAY_INFO, {
          province: addobjAddress.province,
          city: addobjAddress.city,
          area: addobjAddress.area,
          activity_id: activityId,
          goodsDiscountCodeId,
          force_platform_seller,
          group_buy_id: groupBuyId,
          is_leader: Number(JSON.parse(isLeader)),
          step_num: stepNum,
          id: itemId,
          m,
          tempSellerId,
          num,
          productId: good.id,
          type,
          lng: this.state.longitude,
          lat: this.state.latitude
        })
        const orderNum = orderInfo.orderNo
        if (orderInfo) {
          if (!(!orderInfo.allowDeliver && orderInfo.allowDeliver !== 0)) {
            this.getAikucunFreight(addobjAddress, num, orderNum)
          }
        }
        if (!orderInfo) {
          const timer = setTimeout(() => {
            clearTimeout(timer)
            Taro.navigateBack()
          }, 1500)
          return
        }
        orderInfo['img'] = orderInfo.goods.img
      } else {
        orderInfo = await http.postCar<OrderInfo>(GET_PAY_INFO, {
          province: addobjAddress.province,
          city: addobjAddress.city,
          area: addobjAddress.area,
          id: itemId,
          goodsDiscountCodeId,
          force_platform_seller,
          m,
          tempSellerId,
          num,
          type,
          lng: this.state.longitude,
          lat: this.state.latitude
        })
        const orderNum = orderInfo.orderNo
        if (orderInfo) {
          if (!(!orderInfo.allowDeliver && orderInfo.allowDeliver !== 0)) {
            this.getAikucunFreight(addobjAddress, num, orderNum)
          }
        }
        if (!orderInfo) {
          const timer = setTimeout(() => {
            clearTimeout(timer)
            Taro.navigateBack()
          }, 1500)
          return
        }
        orderInfo['img'] = good.images[0].url
      }
      let fromGoodDetail: any
      if (fromOrderNum) {
        fromGoodDetail = await http.postCar(TRANS_ORDER_DETAIL + fromOrderNum, {})
        if (fromGoodDetail && fromGoodDetail.trans_price != null) {
          this.setState({fromGoodDetail, fromOrderNum})
        }
      }
      const custom_config: any = []
      if (fromGoodDetail) {
        const custom_item_detail = JSON.parse(fromGoodDetail.custom_item_detail)
        if (custom_item_detail.custom_item_config) {
          if (custom_item_detail.custom_item_config.arr[0]) {
            const obj = custom_item_detail.custom_item_config.arr
            for (const key in obj) {
              custom_config.push({
                keyName: obj[key].field,
                required: obj[key].ckd || false,
                name: obj[key].k,
                value: obj[key].value || '',
              })
            }
          }
        }
      } else {
        if (orderInfo.goods && orderInfo.goods.custom_item_config) {
          const obj = JSON.parse(orderInfo.goods.custom_item_config)
          for (const key in obj) {
            custom_config.push({
              keyName: key,
              required: obj[key].ckd,
              name: obj[key].k,
              value: obj[key].value || '',
            })
          }
        }
      }
      this.setState({
        custom_config
      })
      if (!orderInfo.id) {
        orderInfo['id'] = itemId
      }
      let givechecked = false
      if (orderInfo.give && !orderInfo.isMail) {
        givechecked = true
      }
      if (fromGoodDetail) {
        givechecked = !!fromGoodDetail.is_self_mention
      }
      orderInfo['title'] = good.name
      orderInfo['num'] = fromGoodDetail ? fromGoodDetail.buy_amount : num
      this.setState({
        orderInfo,
        isOpenCredit: orderInfo.isOpenCredit || 0,
        creditAmount: orderInfo.creditAmount || 0,
        givechecked
      }, () => {
        if (activityId) {
          orderInfo['groupPrice'] = groupPrice
          if (orderInfo.is_group_leader_receive === '1' && orderInfo.leader_receive_rule === '2') {
            this.setState({isChecked: true})
          }
        }
        this.sumMoney(orderInfo, false, true)
      })
      /* 立即购买按钮进入结束 */
    } else { /* 购物车进入 */
      if (!no) {
        Taro.showToast({title: '参数错误', icon: 'none'})
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.navigateBack()
        }, 1500)
        return
      }
      const orderCar: any = await http.postCar<OrderCar>(GET_PAY_INFO, {
        province: addobjAddress.province,
        city: addobjAddress.city,
        area: addobjAddress.area,
        orderNo: no,
        type,
        tempSellerId,
        lng: this.state.longitude,
        lat: this.state.latitude
      })
      if (orderCar) {
        if (orderCar.remit.goods.length === 1) {
          orderCar.remit.goods[0].order_num = no
        }
        if (orderCar.remit.goods && orderCar.remit.goods.length > 0 && !(!orderCar.remit.goods[0].allowDeliver && orderCar.remit.goods[0].allowDeliver !== 0)) {
          this.getAikucunFreightCar(addobjAddress, orderCar.remit.goods)
          this.setState({isShowAikucunFreightFreight: true})
        }
      }
      if (!orderCar) {
        Taro.showToast({title: '生成订单失败', icon: 'none'})
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.navigateBack()
        }, 1500)
        return
      }
      const idsary: any = []
      if (orderCar.self.goods && orderCar.self.goods.length > 0) {
        orderCar.self.goods.map((itmes) => {
          if (itmes.selfList.indexOf(orderCar.self.id) > -1) {
            itmes['self'] = {
              id: orderCar.self.id,
              name: orderCar.self.name,
              address: orderCar.self.address,
            }
          }
          itmes['custom_config'] = []
          if (itmes.custom_item_config) {
            const obj = JSON.parse(itmes.custom_item_config)
            for (const key in obj) {
              itmes['custom_config'].push({
                keyName: key,
                required: obj[key].ckd,
                name: obj[key].k,
                value: obj[key].value || '',
              })
            }
          }
          idsary.push(itmes.id)
        })
      }
      if (orderCar.remit.goods && orderCar.remit.goods.length > 0) {
        for (const item in orderCar.remit.goods) {
          orderCar.remit.goods[item]['custom_config'] = []
          if (orderCar.remit.goods[item].custom_item_config) {
            const obj = JSON.parse(orderCar.remit.goods[item].custom_item_config)
            for (const key in obj) {
              orderCar.remit.goods[item]['custom_config'].push({
                keyName: key,
                required: obj[key].ckd,
                name: obj[key].k,
                value: obj[key].value || '',
              })
            }
          }
        }
      }
      orderCar['orderNo'] = no
      await this.setState({
        orderCar,
        isOpenCredit: orderCar.isOpenCredit || 0,
        creditAmount: orderCar.creditAmount || 0,
        ids: idsary.join(',')
      })
      await this.sumCarMoney(orderCar)
    }
    let userOk = 1
    if (TARO_ENV === 'weapp') {
      // 检查用户有没有授权头像手机号
      userOk = await user.checkUserInfo()
      if (userOk == 2) {
        Taro.login().then(async code => {
          user.code = code.code
          const ret = await user.doLogin({
            nickName: '',
            gender: 1,
            language: '',
            city: '',
            province: '',
            country: '',
            avatarUrl: '',
            bindSellerId: 0,
            itemUUID: '',
            path: ''
          })
          if (!ret) {
            Taro.showToast({
              title: '授权失败,请退出小程序重试',
              icon: 'none'
            })
            return
          }
        })
      }
    }
    let addobj = await http.carGet<Address>(ADDRESS_DEFAULT)
    if (!addobj) {
      addobj = false
    }
    this.setState({addobj, userOk, loadMoreStatus: 'noMore'})
  }

  async componentDidShow() {
    const curPageData: any = Taro.getCurrentInstance().page.data
    const isLogin = await user.checkLogin()
    if (this.state.GOlogin) {
      await this.getData()
    }
    this.setState({env: this.params.env})
    const {type, orderInfo, orderCar, whereSelf, recharge, pay} = this.state
    if (!isLogin) {
      user.jumpLogin()
      return
    }
    let addobj: any = this.state.addobj;
    if (process.env.TARO_ENV != 'h5') {
      addobj = curPageData.add;
    } else {
      addobj = curPageData.addobj;
    }
    if (addobj && addobj.id) {
      const ret = await http.carGet<Address>(ADDRESS_DETAIL, {id: addobj.id})
      this.setState({addobjAddress: ret})
      if (JSON.stringify(orderInfo) !== '{}') {
        if (!(!orderInfo.allowDeliver && orderInfo.allowDeliver !== 0)) {
          this.getAikucunFreight(ret, this.state.buyAmount, this.state.orderNum)
        }
      }
      if (JSON.stringify(orderCar) !== '{}') {
        if (orderCar.remit.goods && orderCar.remit.goods.length > 0 && !(!orderCar.remit.goods[0].allowDeliver && orderCar.remit.goods[0].allowDeliver !== 0)) {
          this.getAikucunFreightCar(ret, this.state.orderCarGoods)
          this.setState({isShowAikucunFreightFreight: true})
        }
      }
      if (!ret) {
        addobj = await http.carGet<Address>(ADDRESS_DEFAULT)
      }
    }
    if (type) {
      if (whereSelf == -1) {
        let access = orderCar.self;
        if (process.env.TARO_ENV != 'h5') {
          access = curPageData.access || orderCar.self
        } else {
          access = curPageData.access || orderCar.self
        }
        if (access && orderCar.self.goods.length > 0) {
          this.getSelfhas(access.id, access.name, access.address)
        }
      } else {
        let access = orderCar.self.goods[whereSelf].self
        if (process.env.TARO_ENV != 'h5') {
          access = curPageData.access || orderCar.self.goods[whereSelf].self
        } else {
          access = curPageData.access || orderCar.self.goods[whereSelf].self
        }
        if (access && orderCar.self.goods.length > 0) {
          this.getSelfhas(access.id, access.name, access.address)
        }
      }
    } else {
      let access = this.state.orderInfo.self;
      if (process.env.TARO_ENV != 'h5') {
        access = curPageData.access || (orderCar.self && orderCar.self.goods[whereSelf].self)
      } else {
        access = curPageData.access || (orderCar.self && orderCar.self.goods[whereSelf].self)
      }
      if (access) orderInfo.self = access
    }

    let redbagId: any = 0;
    let redbag: any = false;
    if (process.env.TARO_ENV != 'h5') {
      redbagId = curPageData.redbagId || 0
      redbag = curPageData.redbag || false
    } else {
      redbagId = curPageData.redbagId || 0
      redbag = curPageData.redbag || false
    }
    this.setState({addobj, redbagId, redbag, orderInfo}, () => {
      if (redbag) {
        if (type) {
          this.sumCarMoney(orderCar)
        } else {
          this.sumMoney(orderInfo)
        }
      }
    })
    if (recharge) {
      const wallet = await http.get(WALLET, {})
      if (wallet) {
        if (type == 0) {
          orderInfo.userBalance = wallet.withdrawBalance
        } else {
          orderCar.userBalance = wallet.withdrawBalance
        }
        if (wallet.withdrawBalance >= pay) {
          this.setState({canBalance: true})
        } else {
          this.setState({canBalance: false})
        }
      }
    }
  }

  params = Taro.getCurrentInstance().router.params

  setRemark(value) {
    this.setState({remark: value})
  }

  checkgrade(val) {
    const {orderInfo, isgrade} = this.state
    const that = this
    if (!isgrade) {
      this.setState({isgrade: true}, () => {
        that.sumMoney(orderInfo, true)
      })
    } else {
      this.setState({isgrade: false}, () => {
        that.sumMoney(orderInfo, true)
      })
    }
  }

  checkgradeKD(val) {
    const {orderInfo, openKD, consume_fee, sum} = this.state
    const that = this
    if (val === 2) {
      if (!openKD) {
        this.setState({openKD: true})
      } else {
        this.setState({openKD: false, consume_fee: 0.00})
      }
    } else {
      if (!openKD) {
        this.setState({openKD: true}, () => {
          that.sumMoney(orderInfo, true)
        })
      } else {
        this.setState({openKD: false, consume_fee: 0.00}, () => {
          that.sumMoney(orderInfo, true)
        })
      }
    }
  }

  giveCheck(val) {
    const {orderInfo} = this.state
    this.setState({givechecked: val}, () => {
      this.sumMoney(orderInfo)
    })
  }

  //切换自提点邮寄 m 为 当前分类 c 为切换后的分类
  giveCheckout(index, m, c) {
    Taro.showLoading({title: '更改中', mask: true})
    const {orderCar} = this.state

    const item = orderCar[m].goods[index]
    orderCar[m].goods.splice(index, 1)
    orderCar[c].goods.unshift(item)
    const idsary = []
    if (orderCar.self.goods) {
      orderCar.self.goods.map((itmes) => {
        idsary.push(itmes.id)
      })
    }
    this.sumCarMoney(orderCar)
    this.setState({orderCar, ids: idsary.join(',')}, () => {
      Taro.hideLoading()
    })
  }

  handleChange(value) {
    const {orderInfo} = this.state
    orderInfo.num = value
    this.getAikucunFreight(this.state.addobjAddress, value, this.state.orderNum)
    this.setState({orderInfo})
    this.sumMoney(orderInfo)
  }

  getStep(info): number {
    if (info.exchange_type === 1) {
      const tmp = (info.exchange_max_integral / (info.exchange_money * 100))
      if (tmp > 1) {
        return Math.ceil(tmp)
      } else {
        return 1
      }
    } else {
      return 1
    }
  }

  getCanUseRedBag() {
    if (process.env.P_ENV === 'lx') {
      return process.env.TARO_ENV !== 'h5'
    }
    return true
  }

  async getIntegralJudge(integral) {
    const {orderInfo, redbag} = this.state
    const goods_id = this.params.itemId
    let price = Number(orderInfo.num) * Number(orderInfo.price)
    if (redbag) {
      const pick = Math.min(...[orderInfo.isred, redbag.amount])
      price = price - Number(pick)
    }
    const ret = await http.postCar(GET_INTEGRAL_JUDGE, {price, integral, goods_id})
    if (ret) {
      if (ret.is_auto_use_integral) {
        ret['num'] = ret.max_integral
      } else {
        ret['num'] = integral
        ret['step'] = this.getStep(ret)
      }
      this.setState({itegralInfo: ret}, () => {
        this.sumMoney(orderInfo)
      })
    }

  }

  async getIntegralJudgeKD(val, integral) {
    // flag: 2购物车结算
    const {orderInfo, redbag, consume_fee, fromGoodDetail, orderCar} = this.state
    if (val === 2) {
      this.setState({consume_fee: integral.toString().match(/^\d+(?:\.\d{0,2})?/)[0]}, () => {
        this.sumCarMoney(orderCar)
      })
    } else {
      this.setState({consume_fee: integral.toString().match(/^\d+(?:\.\d{0,2})?/)[0]}, () => {
        this.sumMoney(orderInfo)
      })
    }
  }

  //单品结算
  async sumMoney(list, isUser = false, flag = true) {
    const {consume_fee, orderInfo, isgrade, redbag, givechecked, itegralInfo, couponMoney, fromGoodDetail, aikucunFreight, ikucunFreightCarTotalFreight, notUse} = this.state
    let couponList = []
    let youhui = 0
    let freight = 0
    let sum = fromGoodDetail ? fromGoodDetail.trans_price : Number(list.num) * Number(list.price)
    if (redbag && !fromGoodDetail) {
      const pick = Math.min(...[list.isred, redbag.amount])
      youhui += Number(pick)
    }
    const originalPrice = sum - youhui
    if (!fromGoodDetail && orderInfo.is_can_use_coupon === 1) {
      couponList = await http.postCar(GET_CAN_USE_COUPONlIST, {
        price: originalPrice.toFixed(2),
        goods_id: list.id
      }) || []
      if (flag && !notUse) { // 调整：默认开启使用优惠券，但在如开关积分等页面刷新的时候，关闭优惠券的不要再打开了
        /* 对优惠券列表进行排序  优惠金额大的放前面 */
        couponList.sort((a: any, b: any) => {
          return Number(b.coupon_discounts_money - a.coupon_discounts_money)
        })
        if (couponList && couponList.length > 0 && !couponMoney) {
          const index = couponList.findIndex(item => item.coupon_discounts_money < sum)
          if (index > -1) {
            this.setState({couponMoney: couponList[index].coupon_discounts_money})
            sum -= couponList[index].coupon_discounts_money
            this.checkMeal(couponList[index])
          }
        }
      }
    }
    if (!fromGoodDetail) {
      if (isgrade) {
        if (itegralInfo) {
          const ret = await http.postCar(GET_INTEGRAL_JUDGE, {
            price: (sum - youhui - couponMoney).toFixed(2),
            integral: itegralInfo.num,
            goods_id: list.id
          })
          if (ret) {
            youhui += Number(ret.deduction_price)
            if (ret.is_auto_use_integral || ret.exchange_type == 2) {
              ret['num'] = ret.max_integral
            } else {
              ret['num'] = itegralInfo.num
              ret['step'] = this.getStep(ret)
            }
            this.setState({itegralInfo: ret})
          } else {
            youhui += Number(itegralInfo.deduction_price)
          }
        } else {
          const ret = await http.postCar(GET_INTEGRAL_JUDGE, {
            price: (sum - youhui).toFixed(2),
            integral: 0,
            goods_id: list.id
          })
          if (ret) {
            youhui += Number(ret.deduction_price)
            if (ret.is_auto_use_integral || ret.exchange_type == 2) {
              ret['num'] = ret.max_integral
            } else {
              ret['num'] = 0
              ret['step'] = this.getStep(ret)
            }
            this.setState({itegralInfo: ret})
          }
        }
      } else {
        const ret = await http.postCar(GET_INTEGRAL_JUDGE, {
          price: (sum - youhui - couponMoney).toFixed(2),
          integral: 0,
          goods_id: list.id
        })
        if (ret) {
          let new_isgrade = false
          if (ret.is_auto_use_integral || ret.exchange_type == 2) {
            if (ret.is_auto_use_integral) {
              if (!isUser) {
                youhui += Number(ret.deduction_price)
                new_isgrade = true
              }
            }
            ret['num'] = ret.max_integral
          } else {
            ret['num'] = 0
            ret['step'] = this.getStep(ret)
          }
          this.setState({itegralInfo: ret, isgrade: new_isgrade})
        }
      }
    }
    sum = sum - youhui - couponMoney
    if (!givechecked) {
      freight = Number(list.freight)
    }
    if (fromGoodDetail) {
      sum = fromGoodDetail.trans_price
      freight = fromGoodDetail.freight
    }
    if (consume_fee && consume_fee > 0) {
      sum = sum - Number(consume_fee)
    }
    sum = sum.toFixed(2)
    this.setState({sum, freight, youhui, couponList})
  }

  //购物车结算
  async sumCarMoney(list, flag = true) {
    const {consume_fee} = this.state
    let sum = 0
    let sum1 = 0
    let sum2 = 0
    let originalPrice = 0 // 原始总价格
    let freight = 0 //邮费
    list.remit.goods.map((item, index) => {
      originalPrice += Number(item.price) * Number(item.num)
      if (item.couponMoney) {
        if ((Number(item.price) * Number(item.num) + item.freight) - item.couponMoney > 0) {
          sum1 += +((Number(item.price) * Number(item.num) + item.freight) - item.couponMoney).toFixed(2)
          item.newFreight = 1
        } else if ((Number(item.price) * Number(item.num)) - item.couponMoney < 0) {
          sum1 += 0
        } else {
          sum1 += (Number(item.price) * Number(item.num)) - item.couponMoney
        }
      } else {
        sum1 += (Number(item.price) * Number(item.num))
      }
      if (item.newFreight) {
        freight += 0
      } else {
        freight += Number(item.freight)
      }
      if (!item.couponMoney && flag) {
        item.canUseCouponList.map((items, i) => this.checItemkMeal(index, 'remit', items, i, list, false))
        this.checkIsUse(index, 'remit')
      }
    })
    list.self.goods.map((item, index) => {
      originalPrice += Number(item.price) * Number(item.num)
      if (item.couponMoney) {
        if ((Number(item.price) * Number(item.num)) - item.couponMoney < 0) {
          sum2 += 0
        } else {
          sum2 += (Number(item.price) * Number(item.num)) - item.couponMoney
        }
      } else {
        sum2 += (Number(item.price) * Number(item.num))
      }
      if (!item.couponMoney && flag) {
        item.canUseCouponList.map((items, i) => this.checItemkMeal(index, 'self', items, i, list, false))
      }
    })
    if (this.state.type != 1) {
      const couponList = (await http.postCar(GET_CAN_USE_COUPONlIST, {
        price: originalPrice.toFixed(2),
        goods_id: list.id
      })) || []
      this.setState({couponList})
    }
    sum = (sum1 + sum2 - Number(consume_fee)).toFixed(2)
    await this.setState({sum, freight})
  }

  getSelfhas(id, name, address) {
    const {orderCar, whereSelf} = this.state
    if (whereSelf < 0) {
      orderCar.self['id'] = id
      orderCar.self['name'] = name
      orderCar.self['address'] = address
      orderCar.self.goods.map((item) => {
        if (item.selfList.indexOf(id) > -1) {
          item['self'] = {id, name, address}
          item['ifNull'] = false
        }
      })
    } else {
      orderCar.self.goods[whereSelf]['self'] = {id, name, address}
      orderCar.self.goods[whereSelf]['ifNull'] = false
    }
    this.setState({orderCar})
  }

  checkPrivate(index) {
    let {latitude, longitude, ids, orderCar} = this.state
    if (index > -1) {
      ids = orderCar.self.goods[index].id
    }
    this.setState({
      whereSelf: index
    })
    Taro.navigateTo({
      url: `/other/address/list?lat=${latitude}&lng=${longitude}&ids=${ids}&selfId=${orderCar.self.id ? orderCar.self.id : ''}`
    })
  }

  agreeCheck(v) {
    this.setState({agree: !v})
  }

  async sureCheck(pay) {
    if (Number(pay) < 0) {
      pay = 0.00
    }
    this.setState({pay})
    const {
      agree,
      formdata,
      type,
      sum,
      orderInfo,
      orderCar,
      addobj,
      givechecked,
      creditAmount
    } = this.state
    if (!agree) {
      Taro.showToast({title: '下单前请阅读并同意服务协议!', icon: 'none'})
      this.setState({userBalance: false})
      return false;
    }
    if (!type) {
      if (givechecked) {
        if (!orderInfo.self) {
          Taro.showToast({title: '请选择自提点!', icon: 'none'})
          return false;
        }
        formdata['selfId'] = orderInfo.self.id
      }
      if (!addobj && !givechecked) {
        Taro.showToast({title: '请选择收货地址!', icon: 'none'})
        return false;
      }
      const check = await this.checkCustom(this.state.custom_config)
      if (!check) {
        Taro.showToast({title: '请填写相关信息', icon: 'none'})
        return false;
      }
    } else {
      //购物车下单
      if (!addobj && orderCar.remit.goods.length > 0) {
        Taro.showToast({title: '请选择收货地址!', icon: 'none'})
        return false;
      }
      if (orderCar.remit.goods) {
        for (const item of orderCar.remit.goods) {
          const check = await this.checkCustom(item.custom_config)
          if (!check) {
            Taro.showToast({title: '请填写相关信息', icon: 'none'})
            return false;
          }
        }
      }

    }
    if (orderCar.self && orderCar.self.goods) {
      orderCar.self.goods.every((item, index) => {
        if (!item.self) {
          const query = Taro.createSelectorQuery();
          query.selectViewport().scrollOffset();
          query.select(`#self_${index}`).boundingClientRect();
          query.exec(res => {
            Taro.pageScrollTo({
              duration: 300,
              scrollTop: res[0].scrollTop + res[index].top - 54,
              success: () => {
                item['ifNull'] = true
                this.setState({
                  orderCar
                })
              }
            })
          })
          return false;
        } else {
          const check = this.checkCustom(item.custom_config)
          if (!check) {
            Taro.showToast({title: '请填写相关信息', icon: 'none'})
            return false;
          }
          return true;
        }
      })
    }
    if (this.state.fromGoodDetail) {
      this.sureOrder(9999)
      return
    }
    if (sum == 0 || sum == 0.00) {
      this.sureOrder(6666)
      return
    }
    if (process.env.P_ENV === 'lx') {
      if (creditAmount) {
        this.setState({userBalance: true})
      } else {
        this.sureOrder(0)
      }
      return false
    }
    const userBalance = orderInfo.userBalance || orderCar.userBalance || 0
    if (process.env.P_ENV === 'kd' && orderInfo.userCoinBalance >= pay) {
      return this.setState({userBalance: true, canBalance: userBalance >= pay})
    }
    if (userBalance >= pay) {
      this.setState({userBalance: true, canBalance: true})
    } else if (userBalance == 0 && !creditAmount) {
      this.sureOrder(0)
    } else {
      this.setState({userBalance: true, canBalance: false})
    }
  }

  onClose() {
    this.setState({userBalance: false})
  }

  sureCheckClose() {
    this.setState({userBalance: false})
  }

  payFn(f) {
    const that = this
    that.setState({userBalance: false})
    that.sureOrder(f)
  }

  chongzhi() {
    this.setState({recharge: true})
    Taro.navigateTo({
      url: '/distributor/wallet/recharge'
    })
  }

  // 跳转支付成功
  paySuccess(id) {
    const _env = this.params.env;
    if (_env == 'pc') {
      this.setState({
        paySuccessShow: true
      });
    } else {
      Taro.redirectTo({url: '/main/order/success?pay=' + id});
    }
  }

  checkGroupStatus(activityId, orderInfo, goodUuid, formdata) {
    if (activityId) {
      Taro.showLoading({title: '加载中...'})
      setTimeout(async () => {
        const data = await http.HPost(CHECK_GROUP_STATUS, {order_num: orderInfo.orderNo})
        if (data.data.status === 1) {
          Taro.hideLoading()
          Taro.redirectTo({url: `/common/group/detail?orderNum=${orderInfo.orderNo}&category=4&itemId=${goodUuid}`})
        }
      }, 2500)
    } else {
      this.paySuccess(formdata.sum.toFixed(2));
    }
  }

  async sureOrder(useAccountPay) {
    const {
      fromGoodDetail,
      fromOrderNum,
      agree,
      isChecked,
      goodUuid,
      formdata,
      remark,
      type,
      sum,
      isgrade,
      orderInfo,
      orderCar,
      redbag,
      redbagId,
      addobj,
      givechecked,
      freight,
      activityId,
      itegralInfo,
      tempSellerId,
      couponIsUseId,
      aikucunFreight,
      ikucunFreightCarTotalFreight,
      consume_fee
    } = this.state
    if (!agree) {
      Taro.showToast({title: '下单前请阅读并同意服务协议!', icon: 'none'})
      this.setState({userBalance: false})
      return false;
    }
    if (consume_fee && consume_fee > 0) {
      formdata['consume_fee'] = consume_fee
    }
    formdata['type'] = type
    formdata['tempSellerId'] = tempSellerId
    formdata['useAccountPay'] = useAccountPay
    formdata['remark'] = remark
    formdata['referSellerId'] = Taro.getStorageSync('bindSellerId') || 0;
    if (!type) {
      //单品 下单
      formdata['sum'] = Number(Number(sum) + Number(freight) + Number(aikucunFreight) + Number(ikucunFreightCarTotalFreight)) < 0 ? 0 : Number(sum) + Number(freight) + Number(aikucunFreight) + Number(ikucunFreightCarTotalFreight)
      if (isgrade) {
        formdata['isgrade'] = Number(itegralInfo.num)
      }
      if (redbag) {
        formdata['redId'] = redbagId
      }
      formdata['num'] = orderInfo.num
      formdata['orderNo'] = orderInfo.orderNo
      formdata['couponIsUseId'] = couponIsUseId
      if (givechecked) {
        if (!orderInfo.self) {
          Taro.showToast({title: '请选择自提点!', icon: 'none'})
          return false;
        }
        formdata['selfId'] = orderInfo.self.id
      }
      if (!addobj) {
        if (givechecked) {
          Taro.showToast({title: '提货需核对您的信息,请去完善!', icon: 'none'})
        } else {
          Taro.showToast({title: '请选择收货地址!', icon: 'none'})
        }
        return false;
      }
      const check = await this.checkCustom(this.state.custom_config)

      if (!check) {
        Taro.showToast({title: '请填写相关信息', icon: 'none'})
        return false;
      } else {
        formdata['customItemDetail'] = JSON.stringify(this.state.custom_config)
      }
      formdata['addressId'] = addobj.id
      formdata['name'] = addobj.name
      formdata['phone'] = addobj.phone
      if (!fromGoodDetail) {
        formdata['useIntegral'] = itegralInfo.is_exchange
      }
    } else {
      //购物车下单
      if (!addobj) {
        Taro.showToast({title: '请选择收货地址!', icon: 'none'})
        return false;
      }
      formdata['is_leader_receive'] = Number(isChecked)
      formdata['useIntegral'] = false
      formdata['name'] = addobj.name
      formdata['phone'] = addobj.phone
      formdata['couponIsUseId'] = couponIsUseId
      if (orderCar.remit && orderCar.remit.goods) {
        formdata['orderNo'] = orderCar.orderNo
        formdata['remit'] = {addressId: addobj.id, goods: []}
        formdata['sum'] = Number(Number(sum) + Number(freight) + Number(aikucunFreight) + Number(ikucunFreightCarTotalFreight)) < 0 ? 0 : Number(sum) + Number(freight) + Number(aikucunFreight) + Number(ikucunFreightCarTotalFreight)
        formdata['freight'] = freight
        orderCar.remit.goods.map((item) => {
          formdata['remit']['goods'].push({
            id: item.id,
            num: item.num,
            couponIsUseId: item.couponIsUseId || 0,
            custom_item_detail: item.custom_config
          })
        })
        formdata['remit'] = JSON.stringify(formdata.remit)
      }
      if (orderCar.self && orderCar.self.goods) {
        formdata['self'] = {}
        formdata['self'] = {goods: []}
        const issure = orderCar.self.goods.every((item, index) => {
          if (!item.self) {
            const query = Taro.createSelectorQuery();
            query.selectViewport().scrollOffset();
            query.select(`#self_${index}`).boundingClientRect();
            query.exec(res => {
              Taro.pageScrollTo({
                duration: 300,
                scrollTop: res[0].scrollTop + res[index].top - 54,
                success: () => {
                  item['ifNull'] = true
                  this.setState({
                    orderCar
                  })
                }
              })
            })
            return false;
          } else {
            formdata['self']['goods'].push({
              id: item.id,
              num: item.num,
              selfId: item.self.id,
              couponIsUseId: item.couponIsUseId || 0,
              custom_item_detail: item.custom_config
            })
            return true;
          }
        })
        if (!issure) {
          Taro.hideLoading()
          return false;
        }
        formdata['self'] = JSON.stringify(formdata.self)
      }
    }
    const that = this
    if (formdata) {
      if (useAccountPay === 6666) {
        Taro.showLoading({title: '结算中...', mask: true})
        const ret = await http.postCar(SURE_ORDER, formdata)
        if (!ret) {
          return this.setState({submiting: false})
        }
        if (ret) {
          that.paySuccess(formdata.sum.toFixed(2));
        } else {
          this.setState({submiting: false})
          return false
        }
        return
      }
      if (useAccountPay == 1) {
        Taro.showModal({
          title: '提示',
          content: '您确定用余额支付吗?',
          cancelText: '取消',
          confirmText: '确定',
          success: async function (res) {
            if (res.confirm) {
              Taro.showLoading({title: '结算中...', mask: true,})
              const ret = await http.postCar(SURE_ORDER, formdata)
              if (!ret) {
                return this.setState({submiting: false})
              }
              if (ret) {
                that.checkGroupStatus(activityId, orderInfo, goodUuid, formdata)
              } else {
                this.setState({submiting: false})
                return false
              }
            }
            if (res.cancel) {
              Taro.hideLoading()
            }
          }
        })
      } else if (useAccountPay == 4) {
        //授信支付
        formdata['creditPay'] = 1
        Taro.showModal({
          title: '提示',
          content: '您确定用授信支付吗?',
          cancelText: '取消',
          confirmText: '确定',
          success: async function (res) {
            if (res.confirm) {
              Taro.showLoading({title: '结算中...', mask: true,})
              const ret = await http.postCar(SURE_ORDER, formdata)
              if (!ret) {
                return this.setState({submiting: false})
              }
              if (ret) {
                that.paySuccess(formdata.sum.toFixed(2));
              } else {
                this.setState({submiting: false})
                return false
              }
            }
            that.setState({submiting: false, alldisable: false})
          }
        })
      } else if (useAccountPay == 5) {
        //授信支付
        formdata['payClass'] = 14
        Taro.showModal({
          title: '提示',
          content: '您确定用蝌蚪币支付吗?',
          cancelText: '取消',
          confirmText: '确定',
          success: async function (res) {
            if (res.confirm) {
              Taro.showLoading({title: '结算中...', mask: true,})
              const ret = await http.postCar(SURE_ORDER, formdata)
              if (!ret) {
                return this.setState({submiting: false})
              }
              if (ret) {
                that.paySuccess(formdata.sum.toFixed(2));
              } else {
                this.setState({submiting: false})
                return false
              }
            }
            that.setState({submiting: false, alldisable: false})
          }
        })
      } else {
        Taro.showLoading({title: '结算中...', mask: true,})
        if (process.env.TARO_ENV === "h5") {
          formdata['paySource'] = 'gongzhonghao'
        }
        if (useAccountPay === 9999) {
          that.setState({submiting: true, alldisable: true})
          formdata['linkman'] = addobj.phone
          const info = await http.postCar(CREATE_AND_PAY + fromOrderNum, formdata)
          if (info) {
            await payment.payment(info)
            Taro.redirectTo({url: '/main/order/success?pay=' + formdata['sum']});
          }
          this.setState({submiting: false})
          return
        }
        let ret = null;
        if (this.state.env != 'pc') {
          ret = await http.postCar(SURE_ORDER, formdata)
          if (!ret) {
            return this.setState({submiting: false})
          }
        }
        ret = ret || formdata['orderNo'];
        if (ret) {
          Taro.hideLoading()
          if (process.env.TARO_ENV === "h5") {
            if (this.state.env == 'pc') {
              const pcQrode = await newHttp.catchGet(CAR_ORDER_QR + ret, formdata)
              if (!pcQrode) {
                Taro.showLoading({title: '下单失败', mask: true,})
                return false;
              }
              this.setState({pcqrcode: pcQrode, pcQrcodeShow: true})
              const time = setInterval(async () => {
                const status = await newHttp.catchGet(PC_ORDER_STATUS + ret)
                if (status.isPay) {
                  clearInterval(time)
                  that.paySuccess(formdata.sum.toFixed(2));
                }
              }, 1000)
            } else {
              if (process.env.P_ENV === 'lx') {
                lxH5Wx.lxPay(ret, (res) => {
                  that.checkGroupStatus(activityId, orderInfo, goodUuid, formdata)
                })
              } else {
                h5Wx.chooseWXPay({...ret}, async res => {
                  that.checkGroupStatus(activityId, orderInfo, goodUuid, formdata)
                }, err => {
                  setTimeout(() => {
                    Taro.redirectTo({url: '/main/order/order?status=0'})
                  }, 1000)
                })
              }
            }
          } else {
            Taro.requestPayment({
              timeStamp: ret.timeStamp,
              nonceStr: ret.nonceStr,
              package: ret.package,
              signType: ret.signType,
              paySign: ret.paySign,
              success: async function (res) {
                that.checkGroupStatus(activityId, orderInfo, goodUuid, formdata)
              },
              fail: function (res) {
                setTimeout(() => {
                  Taro.redirectTo({url: '/main/order/order?status=0'})
                }, 1000)
              }
            })
          }
        } else {
          this.setState({submiting: false})
          return false
        }
      }
    }
  }

  async checkCustom(custom_config) {
    let check = true
    if (custom_config && custom_config.length > 0) {
      for (const item of custom_config) {
        if (item.required) {
          if (!item.value) {
            check = false
            break;
          }
        }
      }
    }
    return check
  }

  setCustom(index, val) {
    const {custom_config} = this.state
    custom_config[index].value = val
    this.setState({custom_config})
  }

  setCustomSelf(index, i, type, val) {
    const {orderCar} = this.state
    orderCar[type].goods[index].custom_config[i].value = val
  }

  openCoupon() {
    const offOpenCoupon = this.state.offOpenCoupon
    this.setState({
      offOpenCoupon: !offOpenCoupon
    })
  }

  getPrice(flag) {
    return (Number(this.state.orderInfo.num) * (flag ? (this.state.orderInfo.price) : (this.state.orderInfo.groupPrice))).toFixed(2)
  }

  openItemCoupon(index, type, offOpenCoupon) {
    const {orderCar} = this.state
    orderCar[type].goods[index]['offOpenCoupon'] = offOpenCoupon
    this.setState({orderCar})
  }

  // 排除已选择的优惠券
  checkIsUse(index2, type) {
    const {orderCar} = this.state
    const arr = []
    if (orderCar[type] && orderCar[type].goods) {
      orderCar[type].goods.map((item, index) => {
        if (orderCar[type].goods[index]['couponIsUseId']) {
          arr.push(orderCar[type].goods[index]['couponIsUseId'])
        }
      })
      orderCar[type].goods.map((item) => {
        item.canUseCouponList.map((i) => {
          i.isUse = arr.indexOf(i.id) <= -1;
        })
      })
    }
  }

  checItemkMeal(index, type, item, couponIndex, list = [], toast = true, flag = true, isClick) {/* 购物车优惠券选择 */
    // index:产品的索引值 item:优惠券信息 couponIndex:优惠券索引值 list:产品信息-订单信息
    let {orderCar} = this.state
    if (JSON.stringify(orderCar) === '{}') {
      orderCar = list
    }
    if (item.isUse == false) {
      if (toast) {
        Taro.showToast({title: '该优惠券已使用', icon: "none"})
      }
      return
    }
    if (item) {
      orderCar[type].goods[index]['offOpenCoupon'] = false
      orderCar[type].goods[index]['notUse'] = false
      orderCar[type].goods[index]['couponMoney'] = item.coupon_discounts_money
      orderCar[type].goods[index]['couponMoneyName'] = item.amount_limit_str
      orderCar[type].goods[index]['couponIsUseId'] = item.id // 循环中赋值，到最后一次循环刚好把最后一张的赋值上
    } else {
      orderCar[type].goods[index]['offOpenCoupon'] = false
      orderCar[type].goods[index]['notUse'] = true
      orderCar[type].goods[index]['couponMoney'] = 0
      orderCar[type].goods[index]['couponMoneyName'] = ''
      orderCar[type].goods[index]['couponIsUseId'] = 0
    }
    if (isClick === 'click') {
      this.checkIsUse(index, type)
    }
    this.setState({
      orderCar
    }, () => {
      this.sumCarMoney(orderCar, flag)
    })
  }

  checkMeal(item) {
    if (item) {
      this.setState({
        offOpenCoupon: false,
        notUse: false,
        couponMoney: item.coupon_discounts_money,
        couponMoneyName: item.amount_limit_str,
        couponIsUseId: item.id
      }, () => {
        if (this.state.type == 1) {
          this.sumCarMoney(this.state.orderCar)
        } else {
          this.sumMoney(this.state.orderInfo)
        }

      })
    } else {
      this.setState({offOpenCoupon: false, notUse: true, couponMoney: 0, couponMoneyName: '', couponIsUseId: 0}, () => {
        if (this.state.type == 1) {
          this.sumCarMoney(this.state.orderCar)
        } else {
          this.sumMoney(this.state.orderInfo, false, false)
        }
      })
    }

  }

  async getPhoneNumber(data) {
    try {
      if (data && data.detail && data.detail.errMsg.indexOf('ok') > -1) {
        const res = await http.post(GET_PHONE, {encryptedData: data.detail.encryptedData, iv: data.detail.iv})
        if (res) {
          this.setState({userOk: 1})
          Taro.showToast({title: '授权成功！'})
        } else {
          Taro.showModal({
            title: '提示',
            content: '需要获取手机号，请打开"使用我的用户信息", 然后再点击登录',
            success: (res) => {
              if (res.confirm) {
                Taro.openSetting()
              } else {
                Taro.navigateBack({
                  delta: 1
                })
              }
            }
          })
          console.log('getPhoneNumber: fail')
        }
      } else {
        user.logout()
      }
    } catch (error) {
      console.error(error)
    }
  }

  handleChangeChecked(e) {
    this.setState({isChecked: e})
  }

  render() {
    const dataColor = Taro.getStorageSync('colorData');
    const {
      consume_fee,
      openKD,
      isChecked,
      fromGoodDetail,
      paySuccessShow,
      pcQrcodeShow,
      pcqrcode,
      loadMoreStatus,
      creditAmount,
      isOpenCredit,
      itegralInfo,
      notUse,
      userOk,
      couponList,
      couponIsUseId,
      couponMoneyName,
      offOpenCoupon,
      platformSet,
      couponMoney,
      orderInfo,
      agree,
      addobj,
      type,
      remark,
      sum,
      freight,
      isgrade,
      givechecked,
      youhui,
      redbag,
      latitude,
      longitude,
      orderCar,
      ids,
      userBalance,
      canBalance,
      activityId,
      isLeader,
      custom_config,
      aikucunFreight,
      allowDeliver,
      denyReason,
      getAikucunFreightCarData,
      isShowAikucunFreightCar,
      isShowAikucunFreightFreight,
      ikucunFreightCarTotalFreight
    } = this.state
    const _env = this.params.env;
    return (
      <View className='place-root'>
        <GzhAuth />
        {activityId && <View className='adddemo'>
          <View className='add-box team-add-box'>
            <View className='at-steps'>
              <View className='at-steps__item at-steps__item--active'>
                <View className='at-steps__circular-wrap'>
                  <View className='at-steps__circular'><AtIcon value='icongift' color='#f73c01' size='24px'
                    prefixClass='car'
                  /></View>
                  <View className='at-steps__right-line' />
                </View>
                <View className='at-steps__title'>
                  <View>选择商品</View>
                  <View>开团/参团</View>
                </View>
              </View>
              <View className='at-steps__item at-steps__item--inactive'>
                <View className='at-steps__circular-wrap'>
                  <View className='at-steps__left-line' />
                  <View className='at-steps__circular'><AtIcon value='iconqunzuduoren' color='#f73c01' size='24px'
                    prefixClass='car'
                  /></View>
                  <View className='at-steps__right-line' />
                </View>
                <View className='at-steps__title'>
                  <View>邀请好友</View>
                  <View>参团支付</View>
                </View>
              </View>
              <View className='at-steps__item at-steps__item--inactive'>
                <View className='at-steps__circular-wrap'>
                  <View className='at-steps__left-line' />
                  <View className='at-steps__circular'><AtIcon value='icona-2tubiaozhizuomoban-01-01'
                    color='#f73c01' size='24px'
                    prefixClass='car'
                  /></View>
                </View>
                <View className='at-steps__title'>
                  <View>人满参团</View>
                  <View>失败退款</View>
                </View>
              </View>
            </View>
          </View>
        </View>}
        <View onClick={()=>{Taro.navigateTo({ url: `/other/address/index?id=${addobj ? addobj.id : 0}`})}} className='adddemo'>
          <View className='add-box team-add-box'>
            {addobj && <View className='add-cont'>
              {addobj.add && <View className='address'>{addobj.add.replace(/,/g, "")}</View>}
              <View className='name'>{addobj.address}</View>
              <View className='address'>{addobj.name} <Text>{addobj.phone}</Text></View>
            </View>}
            {!addobj && <View className='addnull'>暂无可用地址,请前往添加</View>}
            <View className='add-icon-right'>
              <AtIcon value='chevron-right' customStyle='font-size: 16px;' size='16' color='#666' />
            </View>
          </View>
        </View>
        {activityId && orderInfo.is_group_leader_receive === '1' && !isLeader &&
          <View className='team-leader-collection'>
            <AtSwitch disabled={orderInfo.leader_receive_rule === '2'} border={false} checked={isChecked}
              onChange={this.handleChangeChecked.bind(this)} title='团长代收包裹'
            />
          </View>}
        {activityId && <View className='delivery-service'>
          <View>配送服务</View>
          <View>
            {!orderInfo.give && <Block>邮寄</Block>}
            {!orderInfo.isMail && <Block>自提</Block>}
          </View>
        </View>}
        {/*单品下单开始*/}
        {!type && <Block>
          <View className='dombox'>
            {givechecked && orderInfo.give && <Navigator
              url={`/other/address/list?lat=${latitude}&lng=${longitude}&ids=${orderInfo.id}&selfId=${orderInfo.self.id}`}
              hoverClass='none' className='add-box'
            >
              <View className='add-icon-left'>
                <AtIcon prefixClass='car' customStyle='font-size: 16px;' value='icondizhi' size='16' color='#fe9f00' />
              </View>
              <View className='add-cont'>
                <View className='name'>自提点</View>
                <View className='address'>{orderInfo.self.address}</View>
              </View>
              <View className='add-icon-right'>
                <AtIcon value='chevron-right' customStyle='font-size: 16px;' size='16' color='#666' />
              </View>
            </Navigator>}
            <View className='good-box'>
              <View className='good-box-top'>
                <Image className='img' src={orderInfo.img + '?x-oss-process=image/resize,w_240'}
                  mode='aspectFill'
                />
                <View className='good-box-info'>
                  <View className='title'>
                    <View className='name'><View className='name-box'>{orderInfo.title}</View>
                      {orderInfo.gname && <View
                        className={orderInfo.gname.length > 10 ? "good-box-lab two-hidden" : "good-box-lab"}
                      >{orderInfo.gname}</View>}
                      {activityId && <View className='group-label'>拼团</View>}
                    </View>
                  </View>
                  <View className='price-num'>
                    <View className='info'>
                      {!fromGoodDetail && <View className='price font-family-price'><Text
                        className='symbol font-family-price'
                      >￥</Text>{activityId ? orderInfo.groupPrice : orderInfo.price}
                      </View>}
                      {/*<View className='num'>{orderInfo.num}</View>*/}
                      {!!this.getMarketPrice() &&
                        <View className='originalPriceColor' style={`color: ${dataColor.originalPriceColor}`}>价格 <Text
                          className='market-price'
                        ><Text className='symbol font-family-price'>￥</Text><Text
                          className='price-market font-family-price'
                        >{this.getMarketPrice()}</Text></Text></View>}
                    </View>
                    {allowDeliver === '1' && <View className={`good-num ${process.env.TARO_ENV}`}><AtInputNumber
                      className='car-num-small'
                      type='number'
                      disabled={fromGoodDetail}
                      min={orderInfo.buy_num_min || 1}
                      max={orderInfo.buy_num_max}
                      step={1}
                      value={orderInfo.num}
                      onChange={this.handleChange.bind(this)}
                    /></View>}
                  </View>
                </View>
              </View>
              {activityId && orderInfo.give && orderInfo.isMail && <View className='good-box-bottom'>
                {!activityId && <View className='label'>配送服务</View>}
                <View className='check-box'>
                  {orderInfo.give && orderInfo.isMail && <Block>
                    <View className='radio-box' onClick={this.giveCheck.bind(this, true)}><Radio checked={givechecked}
                      color='#fe9f00'
                      value={givechecked}
                    /> 自提</View>
                    <View className='radio-box' onClick={this.giveCheck.bind(this, false)}><Radio
                      checked={!givechecked}
                      color='#fe9f00'
                      value={!givechecked}
                    /> 邮寄</View>
                  </Block>}
                </View>
              </View>}
              {!activityId && <View className='good-box-bottom'>
                <View className='label'>配送服务</View>
                <View className='check-box'>
                  {orderInfo.give && orderInfo.isMail && <Block>
                    <View className='radio-box' onClick={this.giveCheck.bind(this, true)}><Radio checked={givechecked}
                      color='#fe9f00'
                      value={givechecked}
                    /> 自提</View>
                    <View className='radio-box' onClick={this.giveCheck.bind(this, false)}><Radio
                      checked={!givechecked}
                      color='#fe9f00'
                      value={!givechecked}
                    /> 邮寄</View>
                  </Block>}
                  {!orderInfo.give && <Block>
                    邮寄
                  </Block>}
                  {!orderInfo.isMail && <Block>
                    自提
                  </Block>}
                </View>
              </View>}
              {allowDeliver === '0' && <View className='deny-reason'>{denyReason}</View>}
              {custom_config && custom_config.length > 0 && custom_config.map((item, index) =>
                <AtInput
                  key={index}
                  className='custom_config'
                  name={item.name}
                  required={item.required}
                  title={item.name}
                  type='text'
                  placeholder='请填写'
                  value={item.value}
                  onChange={this.setCustom.bind(this, index)}
                />
              )}
              <View className='goods-num-xj'>
                <View className='total-nums'>共{orderInfo.num}件</View>
                {!!activityId && <View className='label'>商品小计：<Text className='symbol font-family-price'
                  style={`color: ${dataColor.priceColor}`}
                >￥</Text><Text
                  className='price font-family-price'
                  style={`color: ${dataColor.priceColor}`}
                >{this.getPrice(false)}</Text></View>}
                {!activityId && <View className='label'>商品小计：<Text className='symbol font-family-price'
                  style={`color: ${dataColor.priceColor}`}
                >￥</Text><Text
                  className='price font-family-price'
                  style={`color: ${dataColor.priceColor}`}
                >{this.getPrice(true)}</Text></View>}
              </View>
            </View>
          </View>
          <View className='dombox'>
            <AtInput
              className='remark'
              name='remark'
              title='留言'
              type='text'
              placeholder='选填,其它需求请备注'
              value={remark}
              onChange={this.setRemark.bind(this)}
            />
            {allowDeliver === '1' && <View className='money group-box'>
              <View className='label'>运费</View>
              <View className='val'
                style={`color: ${dataColor.priceColor}`}
              >￥{aikucunFreight}</View>
            </View>}
            {this.getCanUseRedBag() && !!orderInfo.isred && !!orderInfo.is_can_use_hongbao &&
              <Navigator url={`/main/my/redbag/list?select=${orderInfo.isred}`} className='redbox group-box'>
                <View className='label'>红包</View>
                {!!redbag && <View className='val'
                  style={`color: ${dataColor.priceColor}`}
                >-￥{redbag ? Math.min(...[redbag.amount, orderInfo.isred]) : 0}</View>}
                {!redbag && <AtIcon value='chevron-right' size='16' color='#666' />}
              </Navigator>}
            {itegralInfo && itegralInfo.is_exchange && !!orderInfo.is_can_use_integral &&
              <View className={`grade group-box ${process.env.TARO_ENV}`}>
                <View className='label'>{process.env.integralName}</View>
                <View
                  className='operate'
                >{(itegralInfo.exchange_type != 2 || itegralInfo.is_auto_use_integral == 0) ? "可抵扣" : "最多抵扣"}<Text>{itegralInfo.deduction_price}元</Text><AtSwitch
                  checked={isgrade} color={`${process.env.mainColor}`} onChange={this.checkgrade.bind(this)}
                />
                  {isgrade && itegralInfo.exchange_type != 2 && <View className='operate-right'><AtInputNumber
                    className='car-num-small'
                    type='number'
                    min={0}
                    max={itegralInfo.max_integral}
                    step={itegralInfo.step}
                    value={itegralInfo.num}
                    disabled={Boolean(itegralInfo.is_auto_use_integral)}
                    onChange={this.getIntegralJudge.bind(this)}
                  /></View>}
                </View>
                <View className='val'
                  style={`color: ${dataColor.priceColor}`}
                >-{isgrade ? itegralInfo.num : '0'}{process.env.integralName}</View>
              </View>}
            {process.env.P_ENV === 'kd' &&
              <View>
                <View className={`grade group-box ${process.env.TARO_ENV}`}>
                  <View className='label'>蝌蚪币</View>
                  <View
                    className='operate'
                  ><Text>可抵扣{consume_fee}元</Text><AtSwitch
                    checked={openKD}
                    color={`${process.env.mainColor}`} onChange={this.checkgradeKD.bind(this, 1)}
                  />
                    <View className='operate-right'>{openKD && <AtInputNumber
                      className='car-num-small'
                      type='number'
                      min={0.00}
                      max={orderInfo.userCoinBalance}
                      step={1}
                      value={consume_fee.toString().match(/^\d+(?:\.\d{0,2})?/)}
                      onChange={this.getIntegralJudgeKD.bind(this, 1)}
                    />}</View>
                  </View>
                  <View className='val'
                    style={`color: ${dataColor.priceColor}`}
                  >-{openKD ? consume_fee : '0'}蝌蚪币</View>
                </View>
                <View className='can-use-coin'>
                  当前可用：{orderInfo.userCoinBalance}蝌蚪币
                </View>
              </View>
            }
            {!!couponList && couponList.length > 0 && !!orderInfo.is_can_use_coupon &&
              <View className='money group-box' onClick={this.openCoupon.bind(this)}>
                <View className='label'>优惠券 <Text className='couponMoneyName'>{couponMoneyName}</Text></View>
                <View className='val'
                  style={`color: ${dataColor.priceColor}`}
                >{couponMoney ? `-￥${couponMoney}` : '去用券'}<AtIcon
                  value='chevron-right' size='16'
                  color='#666'
                /></View>
              </View>}
            {activityId && orderInfo.is_group_leader_discount === '1' && isLeader && <View className='money group-box'>
              <View className='label'>活动优惠 <Text className='team-leader-discount'
                style={`color: ${dataColor.titleColor}`}
              >团长优惠</Text></View>
              <View className='val'
                style={`color: ${dataColor.priceColor}`}
              >-￥ {(Number(sum) + Number(freight)).toFixed(2)}</View>
            </View>}
            {!fromGoodDetail && <View className='money group-box'>
              <View className='label'>商品金额</View>
              <View className='val'
                style={`color: ${dataColor.priceColor}`}
              >￥{activityId ? orderInfo.groupPrice : orderInfo.price}</View>
            </View>}
            {!!orderInfo.freight && !givechecked && <View className='freight group-box'>
              <View className='label'>运费</View>
              <View className='val' style={`color: ${dataColor.priceColor}`}>+￥{orderInfo.freight}</View>
            </View>}
            <View className='moneying'>
              <View className='label'>应付:</View>
              <View className='val'
                style={`color: ${dataColor.priceColor}`}
              >￥{Number((Number(sum) + Number(freight) + aikucunFreight).toFixed(2)) < 0 ? 0.00 : (Number(sum) + Number(freight) + aikucunFreight).toFixed(2)}</View>
            </View>
          </View>
        </Block>}
        {/*单品下单结束*/}
        {loadMoreStatus == 'loading' &&
          <AtLoadMore status={loadMoreStatus} moreBtnStyle='border:none;' loadingText='加载中~'
            noMoreText=''
          ></AtLoadMore>}
        {/*购物车下单开始*/}
        {!!type && <Block>
          {orderCar.remit && orderCar.remit.goods.length > 0 && <View className='listbox'>
            <View className='head-title'><Image className='img'
              src={RESOURCE_URL + "/resources/weapp/images/youjiIcon.png"}
              mode='aspectFit'
            />邮寄 <Text
              className='head-title-rt'
            >共{orderCar.remit.goods.length}个商品</Text></View>
            {orderCar.remit.goods.map((item, index) =>
              <View className='good-box'>
                <View className='good-box-top' key={index}>
                  <Image className='img' src={item.img} mode='aspectFill' />
                  <View className='good-box-info'>
                    <View className='title'>
                      <View className='name'><View className='name-box'>{item.title}</View></View>
                      <View className='info'>
                        <View>￥{item.price}</View><View style='font-size:24rpx'>x{item.num}</View>
                      </View>
                    </View>
                    {getAikucunFreightCarData[index] && getAikucunFreightCarData[index].allowDeliver === '1' &&
                      <View className='title'>
                        <View className='name'><View className='name-box'>运费</View></View>
                        <View className='info'>
                          <View>￥{getAikucunFreightCarData[index].freight}</View>
                        </View>
                      </View>}
                    <View className='good-box-lab-box'>
                      {item.gname && <View className='good-box-lab'>{item.gname}</View>}
                    </View>
                  </View>
                </View>
                <View className='good-box-bottom'>
                  <View className='label'>配送服务</View>
                  <View className='check-box'>
                    {item.give && item.isMail && <Block>
                      <View className='radio-box' onClick={this.giveCheckout.bind(this, index, 'remit', 'self')}><Radio
                        checked={!item.isMail} color='#fe9f00'
                      ></Radio> 自提</View>
                      <View className='radio-box'><Radio
                        checked={item.isMail} color='#fe9f00'
                      ></Radio> 邮寄</View>
                    </Block>}
                  </View>
                </View>
                {item.canUseCouponList && !!item.canUseCouponList.length &&
                  <Block><View className='coupon_config' onClick={this.openItemCoupon.bind(this, index, 'remit', true)}>
                    <View className='label'>优惠券 <Text>{item.couponMoneyName}</Text></View>
                    <View className='val'>{item.couponMoney ? `-￥${item.couponMoney}` : '去用券'}<AtIcon
                      value='chevron-right' size='16' color='#666'
                    /></View>
                  </View>
                    <Block>
                      <AtFloatLayout isOpened={item.offOpenCoupon} title='店铺优惠' className='layout-coupon-place'
                        onClose={this.openItemCoupon.bind(this, index, 'remit', false)} scrollY
                      >
                        {item.canUseCouponList.map((val, i) =>
                          <View className='group-item' key={i}
                            onClick={this.checItemkMeal.bind(this, index, 'remit', val, i, [], true, false, 'click')}
                          >
                            <View className='group-nametop'>{val.name}</View>
                            <View className='group-product'>
                              <View
                                className='group-name'
                              >{val.amount_limit_str}<Text
                                style={`color: ${dataColor.priceColor}`}
                              >-￥{val.coupon_discounts_money}</Text></View>
                              {/*isUse:是否禁用  val.id:优惠券的id  item.couponIsUseId:产品使用的优惠券id  item.notUse:产品是否用过优惠券*/}
                              <View
                                className={`group-check ${val.isUse ? '' : 'coupon-active'} `}
                              >{(val.id == item.couponIsUseId && !item.notUse) ?
                                <View className='checkbox__input is-checked'><View className='checkbox__inner'
                                  style='background-color: #f0a33f;'
                                /></View> :
                                <View className={`only ${val.isUse == false ? 'coupon-active' : ''} `}></View>}</View>
                            </View>
                          </View>
                        )}
                        <View className='group-item'>
                          <View className='group-product'
                            onClick={this.checItemkMeal.bind(this, index, 'remit', '', null, [], true, false, 'click')}
                          >
                            <View>不使用优惠券</View>
                            <View className='group-check'>{item.notUse ?
                              <View className='checkbox__input is-checked'><View className='checkbox__inner'
                                style='background-color: #f0a33f;'
                              /></View> :
                              <View className='only'></View>}</View>
                          </View>
                        </View>
                      </AtFloatLayout>
                    </Block>
                  </Block>}
                {getAikucunFreightCarData[index] && getAikucunFreightCarData[index].allowDeliver === '0' &&
                  <View className='deny-reason-car'>{getAikucunFreightCarData[index].denyReason}</View>}
                {item.custom_item_config && item.custom_config && item.custom_config.length > 0 &&
                  <Block>{item.custom_config.map((list, i) =>
                    <AtInput
                      key={i}
                      className='custom_config'
                      name={list.name}
                      required={list.required}
                      title={list.name}
                      type='text'
                      placeholder='请填写'
                      value={list.value}
                      onChange={this.setCustomSelf.bind(this, index, i, 'remit')}
                    />
                  )}
                  </Block>
                }
              </View>
            )}
          </View>}
          {orderCar.self && orderCar.self.goods.length > 0 && <View className='listbox'>
            <View className='head-title'><Image className='img'
              src={RESOURCE_URL + "/resources/weapp/images/zitiIcon.png"}
              mode='aspectFit'
            />自提 <Text>共{orderCar.self.goods.length}个商品</Text></View>
            <View onClick={this.checkPrivate.bind(this, -1)} className='add-box'>
              <View className='add-icon-left'>
                <AtIcon prefixClass='car' value='icondizhi' size='16' color='#fe9f00' />
              </View>
              <View className='add-cont'>
                <View className='name'>自提点</View>
                <View className='address'>{orderCar.self.address}</View>
              </View>
              <View className='add-icon-right'>
                <AtIcon value='chevron-right' size='16' color='#666' />
              </View>
            </View>
            {orderCar.self.goods.map((item, index) =>
              <View className='good-box' key={index}>
                <View className='good-box-top'>
                  <Image className='img' src={item.img} mode='aspectFill' />
                  <View className='good-box-info'>
                    <View className='title'>
                      <View className='name'><View className='name-box'> {item.title}</View></View>
                      <View className='info'><View>￥{item.price}</View><View style='font-size:24rpx'>x{item.num}</View></View>
                    </View>
                    <View className='good-box-lab-box'>{item.gname &&
                      <View className='good-box-lab'>{item.gname}</View>}</View>
                  </View>
                </View>
                <View className='good-box-bottom'>
                  <View className='label'>配送服务</View>
                  <View className='check-box'>
                    {item.give && item.isMail && <Block>
                      <View className='radio-box'><Radio checked={item.give} color='#fe9f00'></Radio> 自提</View>
                      <View className='radio-box' onClick={this.giveCheckout.bind(this, index, 'self', 'remit')}><Radio
                        checked={!item.give} color='#fe9f00'
                      ></Radio> 邮寄</View>
                    </Block>}
                    {!item.isMail && <Block>
                      自提
                    </Block>}
                  </View>
                </View>
                <View className='private-self' id={`self_${index}`} onClick={this.checkPrivate.bind(this, index)}>
                  <View className='label'>自提点</View>
                  <View className={item.self ? "address" : 'address null'}>
                    {item.self ? item.self.address : '选择自提点'}
                  </View>
                  <View className='right'>
                    <AtIcon value='chevron-right' size='16' color='#666' />
                  </View>
                </View>
                {item.selfList.indexOf(orderCar.self.id) == -1 && !item.self &&
                  <View className={item.ifNull ? "ifnull show" : "ifnull"}>{item.ifNull &&
                    <AtIcon prefixClass='car' value='iconjingshi' size='16'
                      color='#ca0000'
                    />}此商品不支持此地点提货,选择其它自提点</View>}
                {item.canUseCouponList && !!item.canUseCouponList.length &&
                  <Block><View className='coupon_config' onClick={this.openItemCoupon.bind(this, index, 'self', true)}>
                    <View className='label'>优惠券 <Text>{item.couponMoneyName}</Text></View>
                    <View className='val'>{item.couponMoney ? `-￥${item.couponMoney}` : '去用券'}<AtIcon
                      value='chevron-right' size='16' color='#666'
                    /></View>
                  </View>
                    <Block>
                      <AtFloatLayout isOpened={item.offOpenCoupon} title='店铺优惠' className='site-discount-method'
                        onClose={this.openItemCoupon.bind(this, index, 'self', false)} scrollY
                      >
                        {item.canUseCouponList.map((val, i) =>
                          <View className='group-item' key={i}
                            onClick={this.checItemkMeal.bind(this, index, 'self', val, i, [], true, true, 'click')}
                          >
                            <View className='group-nametop'>{val.name}</View>
                            <View className='group-product'>
                              <View
                                className='group-name'
                              >{val.amount_limit_str}<Text
                                style={`color: ${dataColor.priceColor}`}
                              >-￥{val.coupon_discounts_money}</Text></View>
                              <View className='group-check'>{(val.id == item.couponIsUseId && !item.notUse) ?
                                <View className='checkbox__input is-checked'><View className='checkbox__inner'
                                  style='background-color: #f0a33f;'
                                /></View> :
                                <View className={`only ${val.isUse == false ? 'coupon-active' : ''} `}></View>}</View>
                            </View>
                          </View>
                        )}
                        <View className='group-item'>
                          <View className='group-product'
                            onClick={this.checItemkMeal.bind(this, index, 'self', '', null, [], true, true, 'click')}
                          >
                            <View>不使用优惠券</View>
                            <View className='group-check'>{item.notUse ?
                              <View className='checkbox__input is-checked'><View className='checkbox__inner'
                                style='background-color: #f0a33f;'
                              /></View> :
                              <View className='only'></View>}</View>
                          </View>
                        </View>
                      </AtFloatLayout>
                    </Block>
                  </Block>}
                {item.custom_item_config && item.custom_config && item.custom_config.length > 0 && item.custom_config.map((list, i) =>
                  <AtInput
                    key={i}
                    className='custom_config'
                    name={list.name}
                    required={list.required}
                    title={list.name}
                    type='text'
                    placeholder='请填写'
                    value={list.value}
                    onChange={this.setCustomSelf.bind(this, index, i, 'self')}
                  />
                )}
              </View>
            )}
          </View>}
          <View className='dombox'>
            <AtInput
              className='remark'
              name='remark'
              title='留言'
              type='text'
              placeholder='选填,其它需求请备注'
              value={remark}
              onChange={this.setRemark.bind(this)}
            />
            {isShowAikucunFreightCar && isShowAikucunFreightFreight && <View className='money group-box'>
              <View className='label'>运费</View>
              <View className='val'
                style={`color: ${dataColor.priceColor}`}
              >￥{ikucunFreightCarTotalFreight}</View>
            </View>}
            {process.env.P_ENV === 'kd' && <View>
              <View className={`grade group-box ${process.env.TARO_ENV}`}>
                <View className='label'>蝌蚪币</View>
                <View
                  className='operate'
                ><Text>可抵扣{consume_fee}元</Text><AtSwitch
                  checked={openKD}
                  color={`${process.env.mainColor}`} onChange={this.checkgradeKD.bind(this, 2)}
                />
                  <View className='operate-right'>{openKD && <AtInputNumber
                    className='car-num-small'
                    type='number'
                    min={0.00}
                    max={orderCar.userCoinBalance}
                    step={0.01}
                    value={consume_fee}
                    onChange={this.getIntegralJudgeKD.bind(this, 2)}
                  />}</View>
                </View>
                <View className='val'
                  style={`color: ${dataColor.priceColor}`}
                >-{openKD ? consume_fee : '0'}蝌蚪币</View>
              </View>
              <View className='can-use-coin'>
                当前可用：{orderCar.userCoinBalance}蝌蚪币
              </View>
            </View>}
            {!!couponList && couponList.length > 0 && !!orderInfo.activity_can_use_coupon &&
              <View className='money group-box' onClick={this.openCoupon.bind(this)}>
                <View className='label'>优惠券</View>
                <View className='val'>{couponMoney ? `-￥${couponMoney}` : '去用券'}<AtIcon value='chevron-right'
                  size='16'
                  color='#666'
                /></View>
              </View>}
            {!!freight && <View className='freight group-box'>
              <View className='label'>运费</View>
              <View className='val'>+￥{freight}</View>
            </View>}
            <View className='moneying'>
              <View className='label'>应付:</View>
              <View className='val'
                style={`color: ${dataColor.priceColor}`}
              >￥{Number((Number(sum) + Number(freight) + Number(ikucunFreightCarTotalFreight)).toFixed(2)) < 0 ? 0.00 : (Number(sum) + Number(freight) + Number(ikucunFreightCarTotalFreight)).toFixed(2)}</View>
            </View>
          </View>
        </Block>}
        {/*购物车下单结束*/}
        <View className='agreement'>
          <View className='check-box-width'><Checkbox value='true' onClick={this.agreeCheck.bind(this, agree)}
            checked={agree}
          /></View>
          {!!platformSet.platform_terms_of_service_new ? <Block>
            {process.env.TARO_ENV === "weapp" &&
              <parser selectable html={platformSet.platform_terms_of_service_new || ''} />}
            {process.env.TARO_ENV === "tt" &&
              <rich-text preview selectable nodes={getContent(platformSet.platform_terms_of_service_new)} />}
            {process.env.TARO_ENV === "h5" &&
              <View dangerouslySetInnerHTML={{__html: platformSet.platform_terms_of_service_new}} />}
          </Block> : <Block>
            <Text>我已经查看并同意"产品抢购须知"和</Text><Navigator
              url='/other/agreement/service'
              className='clause'
            >"{platformSet.platform_terms_of_service}"</Navigator>
          </Block>}
        </View>
        {orderInfo.warn_info &&
          <View className='group-tip-warning'><View className='group-warn_info'><AtIcon size='12px' color='red'
            value='icon icon-gantanhao-sanjiaokuang'
          /><Text
            className='text-warn_info'
          >{orderInfo.warn_info}</Text></View></View>}
        <View className='bottom-pay'>
          <View className='left'>
            <View className='pay'>应付:<Text className='val'
              style={`color: ${dataColor.priceColor}`}
            >￥<Text className='text-num-pay'
              style={`color: ${dataColor.priceColor}`}
            >{Number((Number(sum) + Number(freight) + Number(aikucunFreight) + Number(ikucunFreightCarTotalFreight)).toFixed(2)) < 0 ? 0.00 : (Number(sum) + Number(freight) + Number(aikucunFreight) + Number(ikucunFreightCarTotalFreight)).toFixed(2)}</Text></Text></View>
            {type != 1 && youhui != 0 &&
              <View className='youhui' style={`color: ${dataColor.priceColor}`}>已优惠 ￥{youhui.toFixed(2)}</View>}
          </View>
          {(allowDeliver === '0' || !isShowAikucunFreightCar) &&
            <View className='right submit-order error-submit'>提交订单</View>}
          {userOk == 1 && allowDeliver !== '0' && isShowAikucunFreightCar &&
            <View className='right submit-order'
              onClick={this.sureCheck.bind(this, (Number(sum) + Number(freight) + Number(aikucunFreight) + Number(ikucunFreightCarTotalFreight)))}
            >提交订单</View>}
          {userOk == 2 && allowDeliver !== '0' && isShowAikucunFreightCar &&
            <Button className='right submit-order' openType='getPhoneNumber'
              onGetPhoneNumber={this.getPhoneNumber.bind(this)}
              onError={(err) => {
                      console.log(err)
                    }}
            >提交订单</Button>
          }

        </View>
        <SupportBar></SupportBar>
        {userBalance && <AtModal isOpened={userBalance} onClose={this.onClose.bind(this)}>
          <AtModalContent>
            <View className='modal-box'>
              <View className='modal-title'>选择支付方式</View>
              {/*{process.env.P_ENV === 'kd' && <Block>
                {orderInfo.userCoinBalance >= (Number(sum) + Number(freight)) ?
                  <View className='modal-item' onClick={this.payFn.bind(this, 5)}><Image
                    src={RESOURCE_URL + "/upload/images/20220130/1643551597986_748.png"}
                  />蝌蚪币支付（剩余￥{type == 1 ? orderCar.userCoinBalance : orderInfo.userCoinBalance}） <View
                    className='right'
                  ><AtIcon
                    value='chevron-right' size='15' color='#c9c9c9'
                  /></View></View> : <View className='modal-item disabled'><Image
                    src={RESOURCE_URL + "/upload/images/20220130/1643551597986_748.png"}
                  />蝌蚪币支付（剩余￥{type == 1 ? orderCar.userCoinBalance : orderInfo.userCoinBalance}） <View
                    className='right'
                  ><AtIcon
                    value='chevron-right' size='15' color='#c9c9c9'
                  /></View></View>}
              </Block>}*/}
              <View className='modal-item' onClick={this.payFn.bind(this, 0)}><Image
                src={RESOURCE_URL + "/resources/weapp/images/wxico.png"}
              />微信支付 <View className='right'><AtIcon
                value='chevron-right' size='15' color='#c9c9c9'
              /></View></View>

              <View className='close-modal' onClick={this.sureCheckClose.bind(this)}><AtIcon value='close' size='15'
                color='#333'
              /></View>
              {process.env.P_ENV !== 'lx' && <Block>{canBalance ?
                <View className='modal-item' onClick={this.payFn.bind(this, 1)}><Image
                  src={RESOURCE_URL + "/resources/weapp/images/yeico.png"}
                />余额（剩余￥{type == 1 ? orderCar.userBalance : orderInfo.userBalance}） <View
                  className='right'
                ><AtIcon value='chevron-right' size='15' color='#c9c9c9' /></View></View>
                :
                <View className='modal-item disabled'><Image
                  src={RESOURCE_URL + "/resources/weapp/images/yeico.png"}
                /><View className='czbox'><View
                  className='cztext'
                >余额（剩余￥{type == 1 ? orderCar.userBalance : orderInfo.userBalance}）</View><View
                  className='cztext'
                >余额不足</View></View>
                  {_env != 'pc' && <View className='right' onClick={this.chongzhi.bind(this)}>去充值</View>}
                </View>
              }</Block>}
              {!!isOpenCredit && !activityId && consume_fee <= 0 &&
                <Block>
                  {(Number(creditAmount) || 0) >= (Number(sum) + Number(freight)) ?
                    <View className='modal-item' onClick={this.payFn.bind(this, 4)}><Image
                      src={RESOURCE_URL + "/resources/weapp/images/xinicon.png"}
                    />授信支付<View
                      className='right'
                    ><AtIcon
                      value='chevron-right' size='15' color='#c9c9c9'
                    /></View></View>
                    :
                    <View className='modal-item disabled'><Image
                      src={RESOURCE_URL + "/resources/weapp/images/xinicon.png"}
                    />授信支付<View
                      className='right'
                    ><AtIcon
                      value='chevron-right' size='15' color='#c9c9c9'
                    /></View></View>
                  }
                </Block>
              }
            </View>
          </AtModalContent>
        </AtModal>}
        {pcQrcodeShow && <View className='curtainRoot'>
          <View className='pc-root'>
            <Image className='pcqrcode' src={pcqrcode} mode='widthFix' />
            <View className='pc-tips'>请用微信扫码支付</View>
            <View onClick={() => {
              this.setState({pcQrcodeShow: false, submiting: false})
            }} className='gzh-close'
            >
              <AtIcon value='close' color='#000' />
            </View>
          </View>
        </View>}
        {paySuccessShow && <View className='curtainRoot'>
          <View className='pc-root'>
            <Icon size='60' type='success' />
            <View style='color: #333; font-size: 18px; margin-top: 20px;'>支付成功</View>
          </View>
        </View>}
        {!!couponList && couponList.length > 0 &&
          <Block><AtFloatLayout isOpened={offOpenCoupon} title='店铺优惠' onClose={this.openCoupon.bind(this)}
            className='site-discount-method' scrollY
          >
            {couponList.map((val, i) =>
              <View className='group-item' key={i} onClick={this.checkMeal.bind(this, val)}>
                <View className='group-nametop'>{val.name}</View>
                <View className='group-product'>
                  <View className='group-name'>{val.amount_limit_str}<Text
                    style={`color: ${dataColor.priceColor}`}
                  >-￥{val.coupon_discounts_money}</Text></View>
                  <View className='group-check'>{(val.id == couponIsUseId && !notUse) ?
                    <View className='checkbox__input is-checked'><View className='checkbox__inner'
                      style='background-color: #f0a33f;'
                    /></View> :
                    <View className='only' />}</View>
                </View>
              </View>
            )}
            <View className='group-item'>
              <View className='group-product' onClick={this.checkMeal.bind(this, '')}>
                <View>不使用优惠券</View>
                <View className='group-check'>{notUse ?
                  <View className='checkbox__input is-checked'><View className='checkbox__inner'
                    style='background-color: #f0a33f;'
                  /></View> :
                  <View className='only' />}</View>
              </View>
            </View>
          </AtFloatLayout>
          </Block>}
      </View>
    );
  }
}

export default Confirm as ComponentClass<PageOwnProps, PageState>
